import React, { useState, useMemo, useCallback, useRef, useEffect } from 'react'
import { VariableSizeList as List, ListChildComponentProps } from 'react-window'
import { Maximize, Minimize, Download } from 'lucide-react'
import { KafkaMessage } from '@/stores/kafkaStore'
import { SearchOptions, HighlightText } from './EnhancedSearch'

interface TableModeViewerProps {
  messages: KafkaMessage[]
  searchOptions?: SearchOptions
  maxHeight?: number
  loading?: boolean
  onExport?: () => void
}

interface TableColumn {
  key: string
  label: string
  width: number
  type: 'string' | 'number' | 'boolean' | 'date' | 'object'
}

// 表格行组件
const TableRow = React.memo(({ index, style, data }: ListChildComponentProps) => {
  const { rows, columns, searchOptions } = data
  
  if (index === 0) {
    // 表头行
    return (
      <div style={style} className="bg-gray-100 border-b-2 border-gray-300 sticky top-0 z-10">
        <div className="flex items-center h-full">
          {columns.map((column: TableColumn, colIndex: number) => (
            <div
              key={column.key}
              className="px-3 py-2 text-sm font-semibold text-gray-700 border-r border-gray-300 flex-shrink-0 truncate"
              style={{ width: column.width }}
              title={column.label}
            >
              {column.label}
            </div>
          ))}
        </div>
      </div>
    )
  }

  // 数据行
  const rowData = rows[index - 1]
  if (!rowData) return null

  return (
    <div style={style} className="border-b border-gray-200 hover:bg-gray-50">
      <div className="flex items-center h-full">
        {columns.map((column: TableColumn, colIndex: number) => {
          const cellValue = rowData[column.key]
          const displayValue = formatCellValue(cellValue, column.type)
          
          return (
            <div
              key={column.key}
              className="px-3 py-2 text-sm text-gray-900 border-r border-gray-200 flex-shrink-0 truncate"
              style={{ width: column.width }}
              title={displayValue}
            >
              {searchOptions?.query && searchOptions.highlightResults ? (
                <HighlightText
                  text={displayValue}
                  searchQuery={searchOptions.query}
                  caseSensitive={searchOptions.caseSensitive}
                  useRegex={searchOptions.useRegex}
                />
              ) : (
                displayValue
              )}
            </div>
          )
        })}
      </div>
    </div>
  )
})

TableRow.displayName = 'TableRow'

// 格式化单元格值
function formatCellValue(value: any, type: string): string {
  if (value === null || value === undefined) return ''
  
  switch (type) {
    case 'date':
      if (typeof value === 'string' && value.includes('T')) {
        return new Date(value).toLocaleString()
      }
      return String(value)
    case 'object':
      if (typeof value === 'object') {
        return JSON.stringify(value)
      }
      return String(value)
    case 'boolean':
      return value ? '是' : '否'
    case 'number':
      return typeof value === 'number' ? value.toLocaleString() : String(value)
    default:
      return String(value)
  }
}

// 检测数据类型
function detectColumnType(values: any[]): 'string' | 'number' | 'boolean' | 'date' | 'object' {
  const nonNullValues = values.filter(v => v !== null && v !== undefined)
  if (nonNullValues.length === 0) return 'string'
  
  const sample = nonNullValues.slice(0, 10) // 取前10个样本
  
  // 检测日期
  if (sample.some(v => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(v))) {
    return 'date'
  }
  
  // 检测布尔值
  if (sample.every(v => typeof v === 'boolean')) {
    return 'boolean'
  }
  
  // 检测数字
  if (sample.every(v => typeof v === 'number' || !isNaN(Number(v)))) {
    return 'number'
  }
  
  // 检测对象
  if (sample.some(v => typeof v === 'object' && v !== null)) {
    return 'object'
  }
  
  return 'string'
}

export default function TableModeViewer({
  messages,
  searchOptions,
  maxHeight = 600,
  loading = false,
  onExport
}: TableModeViewerProps) {
  const [columnWidths, setColumnWidths] = useState<Record<string, number>>({})
  const [isFullscreen, setIsFullscreen] = useState(false)
  const containerRef = useRef<HTMLDivElement>(null)

  // 解析消息数据，提取所有可能的列
  const { columns, rows } = useMemo(() => {
    if (messages.length === 0) {
      return { columns: [], rows: [] }
    }

    // 收集所有可能的字段
    const allFields = new Set<string>()
    const fieldValues: Record<string, any[]> = {}

    messages.forEach(message => {
      if (typeof message.value === 'object' && message.value !== null) {
        Object.keys(message.value).forEach(key => {
          allFields.add(key)
          if (!fieldValues[key]) fieldValues[key] = []
          fieldValues[key].push(message.value[key])
        })
      }
    })

    // 生成列定义
    const columns: TableColumn[] = Array.from(allFields).map(field => {
      const values = fieldValues[field] || []
      const type = detectColumnType(values)
      
      // 计算列宽
      const maxLength = Math.max(
        field.length,
        ...values.slice(0, 100).map(v => String(v || '').length)
      )
      const width = Math.min(Math.max(maxLength * 8 + 24, 100), 300)
      
      return {
        key: field,
        label: field,
        width: columnWidths[field] || width,
        type
      }
    }).sort((a, b) => {
      // 常见字段排序
      const priority = ['id', 'type', 'content', 'timestamp', 'status']
      const aIndex = priority.indexOf(a.key)
      const bIndex = priority.indexOf(b.key)
      
      if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex
      if (aIndex !== -1) return -1
      if (bIndex !== -1) return 1
      return a.key.localeCompare(b.key)
    })

    // 生成行数据
    const rows = messages.map(message => {
      const row: Record<string, any> = {}
      if (typeof message.value === 'object' && message.value !== null) {
        columns.forEach(column => {
          row[column.key] = message.value[column.key]
        })
      }
      return row
    })

    return { columns, rows }
  }, [messages, columnWidths])

  // 过滤行数据
  const filteredRows = useMemo(() => {
    if (!searchOptions?.query) return rows

    const query = searchOptions.caseSensitive 
      ? searchOptions.query 
      : searchOptions.query.toLowerCase()

    return rows.filter(row => {
      return columns.some(column => {
        const cellValue = formatCellValue(row[column.key], column.type)
        const searchText = searchOptions.caseSensitive 
          ? cellValue 
          : cellValue.toLowerCase()

        if (searchOptions.useRegex) {
          try {
            const flags = searchOptions.caseSensitive ? 'g' : 'gi'
            const regex = new RegExp(searchOptions.query, flags)
            return regex.test(searchText)
          } catch {
            return false
          }
        } else {
          return searchText.includes(query)
        }
      })
    })
  }, [rows, columns, searchOptions])

  // 计算行高
  const getItemSize = useCallback((index: number) => {
    return index === 0 ? 40 : 32 // 表头40px，数据行32px
  }, [])

  // 全屏功能
  const toggleFullscreen = useCallback(() => {
    if (!containerRef.current) return

    if (!isFullscreen) {
      // 进入全屏
      if (containerRef.current.requestFullscreen) {
        containerRef.current.requestFullscreen()
      } else if ((containerRef.current as any).webkitRequestFullscreen) {
        (containerRef.current as any).webkitRequestFullscreen()
      } else if ((containerRef.current as any).msRequestFullscreen) {
        (containerRef.current as any).msRequestFullscreen()
      }
    } else {
      // 退出全屏
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if ((document as any).webkitExitFullscreen) {
        (document as any).webkitExitFullscreen()
      } else if ((document as any).msExitFullscreen) {
        (document as any).msExitFullscreen()
      }
    }
  }, [isFullscreen])

  // 监听全屏状态变化
  useEffect(() => {
    const handleFullscreenChange = () => {
      setIsFullscreen(!!document.fullscreenElement)
    }

    document.addEventListener('fullscreenchange', handleFullscreenChange)
    document.addEventListener('webkitfullscreenchange', handleFullscreenChange)
    document.addEventListener('msfullscreenchange', handleFullscreenChange)

    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange)
      document.removeEventListener('webkitfullscreenchange', handleFullscreenChange)
      document.removeEventListener('msfullscreenchange', handleFullscreenChange)
    }
  }, [])

  // 导出CSV功能
  const handleExportCSV = useCallback(() => {
    if (filteredRows.length === 0) return

    // 生成CSV内容
    const headers = columns.map(col => col.label).join(',')
    const csvContent = [
      headers,
      ...filteredRows.map(row =>
        columns.map(col => {
          const value = formatCellValue(row[col.key], col.type)
          // 处理包含逗号的值
          return value.includes(',') ? `"${value.replace(/"/g, '""')}"` : value
        }).join(',')
      )
    ].join('\n')

    // 下载文件
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `kafka_messages_${new Date().toISOString().slice(0, 19)}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }, [filteredRows, columns])

  // 传递给虚拟化行的数据
  const itemData = useMemo(() => ({
    rows: filteredRows,
    columns,
    searchOptions
  }), [filteredRows, columns, searchOptions])

  // 计算表格高度
  const tableHeight = isFullscreen ? window.innerHeight - 120 : maxHeight

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
        <span className="ml-2 text-gray-600">加载中...</span>
      </div>
    )
  }

  if (messages.length === 0) {
    return (
      <div className="text-center py-12">
        <h3 className="text-lg font-medium text-gray-900 mb-2">暂无数据</h3>
        <p className="text-gray-600">没有找到消息数据</p>
      </div>
    )
  }

  if (columns.length === 0) {
    return (
      <div className="text-center py-12">
        <h3 className="text-lg font-medium text-gray-900 mb-2">无法解析数据</h3>
        <p className="text-gray-600">消息的Value不是有效的JSON对象</p>
      </div>
    )
  }

  return (
    <div
      ref={containerRef}
      className={`border border-gray-200 rounded-lg overflow-hidden ${
        isFullscreen ? 'fixed inset-0 z-50 bg-white' : ''
      }`}
    >
      {/* 表格信息和控制栏 */}
      <div className="bg-gray-50 px-4 py-2 border-b border-gray-200">
        <div className="flex items-center justify-between">
          <div className="text-sm text-gray-600">
            {columns.length} 列 × {filteredRows.length} 行
            {searchOptions?.query && (
              <span className="ml-2 text-primary-600">
                (从 {rows.length} 行中筛选)
              </span>
            )}
          </div>

          {/* 控制按钮 */}
          <div className="flex items-center space-x-2">
            <div className="text-xs text-gray-500">
              💡 表格模式：仅显示消息Value的结构化数据
            </div>

            {/* 导出按钮 */}
            <button
              onClick={handleExportCSV}
              disabled={filteredRows.length === 0}
              className="p-2 text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded disabled:opacity-50 disabled:cursor-not-allowed"
              title="导出CSV"
            >
              <Download className="h-4 w-4" />
            </button>

            {/* 全屏按钮 */}
            <button
              onClick={toggleFullscreen}
              className="p-2 text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded"
              title={isFullscreen ? "退出全屏" : "全屏显示"}
            >
              {isFullscreen ? (
                <Minimize className="h-4 w-4" />
              ) : (
                <Maximize className="h-4 w-4" />
              )}
            </button>
          </div>
        </div>
      </div>

      {/* 虚拟化表格 */}
      <List
        height={tableHeight}
        itemCount={filteredRows.length + 1} // +1 for header
        itemSize={getItemSize}
        itemData={itemData}
        overscanCount={5}
      >
        {TableRow}
      </List>
    </div>
  )
}
